package br.mikhas.container.scope;

import javassist.util.proxy.ProxyObject;
import br.mikhas.container.config.BeanDefinition;
import br.mikhas.container.factory.BeanFactory;
import br.mikhas.container.factory.BeanPostProcessor;
import br.mikhas.reflector.ProxyUtils;

public class ScopedBeanPostProcessor implements BeanPostProcessor {

	private BeanFactory beanFactory;

	@Override
	public boolean mayProcess(BeanDefinition definition) {
		return isScoped(definition);
	}

	private boolean isScoped(BeanDefinition definition) {
		return ProxyUtils.isProxyClass(definition.getInstantiatingClass());
	}

	@Override
	public Object processBean(BeanDefinition definition, Object resource) {
		ProxyObject proxy = (ProxyObject) resource;

		ScopeProxyMethodHandler handler = (ScopeProxyMethodHandler) proxy
				.getHandler();

		handler.setBeanFactory(beanFactory);

		return resource;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

}
